package com.l024.hi_device_util.message;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;

import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wu_ming_zhi_bei
 * @date 2021/6/1 18:02
 * @Notes
 */
public class MessageUtil {
    public static String permission = Manifest.permission.READ_SMS;
    public static final int MESSAGE_CODE = 1002;
    /**
     * 所有的短信
     */
    public static final String SMS_URI_ALL = "content://sms/";
    /**
     * 收件箱短信
     */
    public static final String SMS_URI_INBOX = "content://sms/inbox";
    /**
     * 发件箱短信
     */
    public static final String SMS_URI_SEND = "content://sms/sent";
    /**
     * 草稿箱短信
     */
    public static final String SMS_URI_DRAFT = "content://sms/draft";


    String[] projection = new String[] { "_id", "address", "person","body", "date", "type"};

    public List<MessageModel> getMessages(Activity activity){
        List<MessageModel> messageModels = new ArrayList<>();
        Uri uri = Uri.parse(SMS_URI_ALL);
        ContentResolver cr = activity.getContentResolver();
        Cursor cusor = cr.query(uri, projection, null, null,"date desc");
        if (cusor != null) {
            int nameColumn = cusor.getColumnIndex("person");
            int phoneNumberColumn = cusor.getColumnIndex("address");
            int smsbodyColumn = cusor.getColumnIndex("body");
            int dateColumn = cusor.getColumnIndex("date");
            int typeColumn = cusor.getColumnIndex("type");
            while (cusor.moveToNext()) {
                MessageModel messageModel = new MessageModel();
                messageModel.setName(cusor.getString(nameColumn));
                messageModel.setDate(cusor.getString(dateColumn));
                messageModel.setPhoneNumber(cusor.getString(phoneNumberColumn));
                messageModel.setSmsbody(cusor.getString(smsbodyColumn));
                messageModel.setType(cusor.getString(typeColumn));
                messageModels.add(messageModel);
            }
            cusor.close();
        }
        return messageModels;
    }

    public boolean checkPermission(Activity activity){
        if(ContextCompat.checkSelfPermission(activity,permission)
                != PackageManager.PERMISSION_GRANTED){
            return false;
        }else{
            return true;
        }
    }
} 